package id.co.rho.scoring.cid.client.widgets;

import id.co.rho.scoring.cid.client.model.ChangeTrackingModel;

import com.extjs.gxt.ui.client.binding.Converter;
import com.extjs.gxt.ui.client.binding.FieldBinding;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.Field;

public class ChangeTrackingSupportComboBoxBinding  extends FieldBinding {
	
	public ChangeTrackingSupportComboBoxBinding(Field field, String property) {
		super(field, property);
		final ComboBox<ModelData> combo = (ComboBox<ModelData>)field;
		setConverter(new Converter(){
			@Override
			public Object convertFieldValue(Object value) {
				if(value instanceof ModelData){
					ModelData val = (ModelData)value;
					return val.get(combo.getValueField());
				}else{
					return value;
				}
			}
			@Override
			public Object convertModelValue(Object value) {
				return combo.getStore().findModel(combo.getValueField(), value);
			}
		});
	}

	/**
	 * Will update the field and update originalValue based on
	 * ChangeTrackingModel's originalValue, ignoring the parameter
	 * updateOriginalValue. If the model is not of type ChangeTrackingModel than
	 * revert to original mechanism.
	 * Assumption: this method will only be called from super.bind().
	 * the call from updateField() (overloaded method with no param) will call super.updateField(boolean).
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void updateField(boolean updateOriginalValue) {
		if (getModel() instanceof ChangeTrackingModel) {
			ChangeTrackingModel model = (ChangeTrackingModel) getModel();
			Object val = onConvertModelValue(model.get(property));
			Object originalVal = onConvertModelValue(model.getOriginal(property));
			
			field.setOriginalValue(originalVal);
			field.setValue(val);

			if(field instanceof DirtyAwareComboBox) {
				((DirtyAwareComboBox)field).resetDirtyness();
			}
		}
		else if(getModel()!=null) {
			super.updateField(updateOriginalValue);
		}
	}

	@Override
	public void updateField() {
		super.updateField(false);
	}

    @Override
    public void bind(ModelData model) {
        super.bind(model);
        if(model!=null){
        	updateField();
        }
    }

}
